package com.example.gamestore.controller;

import com.example.gamestore.pojo.LoginInfo;
import com.example.gamestore.pojo.User;
import com.example.gamestore.service.LoginInfoService;
import com.example.gamestore.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zihao
 * @date 2025/6/6 9:08
 * @VERSION
 * @description
 **/
@CrossOrigin//前后端允许跨域
@Slf4j //日志对象,用来代替我们写的各种输出语句
@Controller
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    private int status;
    @Autowired
    private UserService userService;

    @Autowired
    private LoginInfoService loginInfoService;

    @GetMapping("/login")
    public String showLoginPage() {
        return "index";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, HttpSession session, Model model) {
        User user = userService.getUserByUsernameAndPassword(username, password);
        if (user != null) {
            session.setAttribute("userId", user.getId()); // 确保存储用户ID到会话
            session.setAttribute("isAdmin", user.getIsAdmin());

            // 保存登录信息
            LoginInfo loginInfo = new LoginInfo();
            loginInfo.setUserId(user.getId());
            loginInfoService.addLoginInfo(loginInfo);

            if (user.getIsAdmin() == 1) {
                return "redirect:/ui";
            } else {
                return "redirect:/home";
            }
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "index";
        }
    }

    @GetMapping("/api/user/id")
    @ResponseBody
    public Long getUserId(HttpSession session) {
        Long userId = (Long) session.getAttribute("userId");
        return userId != null ? userId : -1; // 返回-1表示未登录
    }



    //用户查询
    @GetMapping("/usermanage")
    public String query(Model model) {
        System.out.println("进入到usercontroller");
        List<User> users = userService.query();
        System.out.println(users);
        model.addAttribute("users", users);
        return "usermanage";
    }

    @PostMapping("/addUser")
    @ResponseBody
    public Map<String, Object> addUser(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 参数验证
            if (user == null || user.getUsername() == null || user.getUsername().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "添加用户失败：用户名不能为空");
                return result;
            }
            // 设置默认值
            if (user.getCreateTime() == null) {
                user.setCreateTime(new Date());
            }
            userService.add(user);
            result.put("success", true);
            result.put("message", "添加用户成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加用户失败：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    // 用户修改
    @PostMapping("/updateUser")
    @ResponseBody
    public Map<String, Object> updateUser(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查用户是否存在
            User existingUser = userService.getUserById(user.getId());
            if (existingUser == null) {
                result.put("success", false);
                result.put("message", "用户不存在，更新失败");
                return result;
            }

            // 更新用户信息
            if (user.getUsername() != null) {
                existingUser.setUsername(user.getUsername());
            }
            if (user.getPassword() != null && !user.getPassword().isEmpty()) {
                existingUser.setPassword(user.getPassword());
            }
            if (user.getEmail() != null) {
                existingUser.setEmail(user.getEmail());
            }
            existingUser.setIsAdmin(user.getIsAdmin());

            userService.updateUser(existingUser);
            result.put("success", true);
            result.put("message", "用户信息更新成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新用户信息失败：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    //用户删除
    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable Long id) {
        userService.delete(id);
        return "redirect:/usermanage";
    }

    // 退出登录方法
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 使会话失效
        session.invalidate();
        // 重定向到登录页面
        return "redirect:/login";
    }

    @PostMapping("/updatePassword")
    public String updatePassword(@RequestParam String oldPassword, @RequestParam String newPassword, @RequestParam String confirmPassword, HttpSession session, Model model) {
        Long userId = (Long) session.getAttribute("userId");
        if (userId == null) {
            model.addAttribute("error", "用户未登录");
            return "setting";
        }
        if (!newPassword.equals(confirmPassword)) {
            model.addAttribute("error", "新密码和确认密码不一致");
            return "setting";
        }
        boolean success = userService.updatePassword(userId, oldPassword, newPassword);
        if (success) {
            model.addAttribute("success", "密码修改成功");
        } else {
            model.addAttribute("error", "旧密码不正确或修改失败");
        }
        return "setting";
    }

    @GetMapping("/getUser/{id}")
    @ResponseBody
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @GetMapping("/register")
    public String showRegisterPage() {
        return "register";
    }

    @PostMapping("/register")
    @ResponseBody
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 参数验证
            if (user == null || user.getUsername() == null || user.getUsername().trim().isEmpty()
                    || user.getPassword() == null || user.getPassword().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "注册失败：用户名或密码不能为空");
                return result;
            }

            // 确保 email 不为空
            if (user.getEmail() == null) {
                result.put("success", false);
                result.put("message", "注册失败：邮箱不能为空");
                return result;
            }

            // 设置默认值
            if (user.getCreateTime() == null) {
                user.setCreateTime(new Date());
            }

            userService.add(user);
            result.put("success", true);
            result.put("message", "注册成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "注册失败：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }



}
